import {request} from "../../utils/util";

let app = getApp()
Page({
  data: {
    top: app.globalData.rightBarInfo.top,
    height: app.globalData.rightBarInfo.height,
    windowHeight: app.globalData.systemInfo.screenHeight,
    type: [],
    classifyId: '',
    list: [],
    page: 1,
    loadMore: true,
  },
  selectType (ev) {
    let { id } = ev.currentTarget.dataset;
    this.setData({
      classifyId: id,
      page: 1,
      loadMore: true
    })
    this.getList(1)
  },
  nav (ev) {
    if (!app.globalData.userInfo.nickname) {
      wx.showToast({
        title: '请先登录',
        icon: 'none',
        duration: 2000
      })
      setTimeout(() => {
        wx.switchTab({
          url: '/pages/mine/index'
        })
      }, 1000)
      return false
    } else if (!app.globalData.userInfo.telephone) {
      wx.showToast({
        title: '请绑定手机号',
        icon: 'none',
        duration: 2000
      })
      setTimeout(() => {
        wx.navigateTo({
          url: '/pages/login/index'
        })
      }, 1000)
      return false
    }
    let { item } = ev.currentTarget.dataset;
    wx.navigateTo({
      url: `/pages/goodsDetail/index?venue_id=${this.options.venue_id}&goods_id=${item.id}`
    })
  },
  // 获取banner数据
  getClassify() {
    request({
      url: '/api/web/shop/classify',
      success: ({ code, data }) => {
        if (code === 200) {
          this.setData({
            type: data,
            classifyId: data[0].id
          })
          this.getList(1)
        }
      }
    })
  },
  // 获取商品列表数据
  getList(page) {
    wx.showLoading({
      title: '加载中..',
      mask: true
    })
    request({
      url: '/api/web/shop/list',
      params: {
        venue_id: this.options.venue_id,
        classify_id: this.data.classifyId,
        page
      },
      success: ({ code, data, message }) => {
        wx.hideLoading()
        if (code === 200) {
          if (data.current_page === 1) {
            this.data.list = []
          }
          this.setData({
            list: [
              ...this.data.list,
              ...data.data
            ],
            page: data.current_page,
            loadMore: data.current_page !== data.last_page
          })
        } else {
          wx.showToast({
            title: message,
            icon: 'none',
            duration: 2000
          })
        }
      }
    })
  },
  onLoadMore() {
    if (!this.data.loadMore) {
      return false
    }
    this.getList(this.data.page + 1)
  },
  onShow () {
    wx.setNavigationBarColor({
      frontColor: '#000000',
      backgroundColor: '#000000',
      animation: {
        duration: 400,
        timingFunc: 'easeIn'
      }
    })
  },
  onLoad() {
    this.getClassify()
  }
})
